import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_rider/event/click_operators_event.dart';
import 'package:flutter_rider/kit/loc_kit.dart';
import 'package:flutter_rider/main/widgets/base/number_layout.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/dialog/loading_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_background.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/ext/u_title_layout.dart';
import 'package:flutter_rider/main/widgets/pop/pop_operator_user_list.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/utils/toast.dart';
import 'package:flutter_svg/svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/refresh_order_event.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/utils/upload_image_helper.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/utils/alib.dart';
import 'package:flutter_rider/module/task/api/load_api.dart';

class OrderLoadPage extends StatefulWidget {
  String id;
  
  OrderLoadPage(this.id, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return OrderLoadPageState();
  }
}

class OrderLoadPageState extends State<OrderLoadPage> {
  final NumberLayoutController _amountLayoutController = NumberLayoutController(0);
  final NumberLayoutController _numberLayoutController = NumberLayoutController(0);
  final _describeTextController = TextEditingController();
  late UploadImageHelper _uploadHelper;
  late StreamSubscription _eventFn1;
  dynamic _data;
  var _unit = 1;
  dynamic _jSkuOptions1;
  String operatorName = "";
  String operatorMobile = "";
  int operatorId = 0;
  List _chooseList = [];
  String str="";

  @override
  void initState() {
    super.initState();
    _uploadHelper = UploadImageHelper(context, maxImages: 6);
    _amountLayoutController.decimal = true;
    _getLoadName();
    _eventFn1 = eventBus.on<ClickOperatorsEvent>().listen((event) {
      List arr = [];
      print(event.chooseList);

      if(event.chooseList.isNotEmpty) {
        for (var element in event.chooseList) {
          arr.add(element.name);
        }
      }
      setState(() {
        str = arr.join(',');
        _chooseList = event.chooseList;
      });

    });

  }

  @override
  void dispose() {
    super.dispose();
    _eventFn1.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: UIColor.color_main,
      appBar: UTitleLayout.getBackTitle(context, "装货"),
      body:  GestureDetector(
        child: StateLayout(
          url: "/waybill_mission/loading_detail?id=${widget.id}&action=load",
          childBuilder: _renderContent,
          dataCallback: _onDataCallback,
          errorCallback: _errorCallback,
        ).padding(EdgeInsets.only(left: MediaQuery.of(context).padding.left, right: MediaQuery.of(context).padding.right)),
        onTap: () {
          Alib.hideKeyboard(context);
        },
      ),
    );
  }

  _onDataCallback(dynamic data) {
    _data = data;
    _unit = _data["unit"];
    _reShowSku();
  }

  _errorCallback(dynamic data, response) {
    if(response.code == 1006032) {
      Future.delayed(const Duration(seconds: 4),(){
        Navigator.of(context).pop();
      });
    }
  }

  _reShowSku() {
    _jSkuOptions1 = jsonDecode(_data["sku_option"]);
  }

  Widget _renderContent(dynamic data) {
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                _renderTop(),
                8.hspace,
                _renderSku(),
                8.hspace,
                _renderBottom(),
                8.hspace,
                ValueListenableBuilder<List<AssetEntity>>(valueListenable: _uploadHelper.getValueNotifier(), builder: (context, value, child) {
                  return _renderUploadImage(value);
                }),
                8.hspace,
                _renderRemark(),
                10.hspace,
              ],
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.all(12.rpx),
          child: UText.getBkButton(
            "装货确认",
            16.rpx,
            bkColor: UIColor.color_primary,
            radius: 12.rpx,
            width: double.infinity,
            height: 48.rpx,
            onPressed: _onClickSubmit,
          ),
        ),
        SizedBox(height: MediaQuery.of(context).padding.bottom),
      ],
    );
  }

  Widget _renderTop() {
    return Container(
          decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child: Column(
          children: [
            Container(
                height: 48.rpx,
                padding: EdgeInsets.symmetric(horizontal: 16.rpx),
                child: Row(
                  children: [
                    UText.get("车辆编号", UIColor.color_t1, 16.rpx),
                    const Spacer(),
                    UText.get(_data["car_no"] ?? "", UIColor.color_primary, 16.rpx),
                  ],
                )
            ),
            Container(
                margin: EdgeInsets.only(left: 16.rpx, right: 16.rpx),
                height: 1.rpx,
                color: UIColor.color_divider),
            GestureDetector(
              onTap: () {
                print("選擇");
                OpenUtils.pop2(context, PopOperatorUserList(1,name:operatorName,mobile:operatorMobile,id:operatorId,chooseList:_chooseList));
              },
              child:Container(
                    height: 48.rpx,
                    padding: EdgeInsets.symmetric(horizontal: 16.rpx),
                    child: Row(
                      children: [
                        UText.get("装货人", UIColor.color_t1, 16.rpx),
                        const Spacer(),
                        // Consumer(builder: (context, ref, _) {
                        //   _chooseList = ref.watch(taskOperatorProvider);

                           LimitedBox(
                            maxWidth: 200.rpx,
                            child:Text(str.isEmpty ?operatorName : str, style: TextStyle(color:UIColor.color_t1,fontSize: 16.rpx,),overflow: TextOverflow.ellipsis,maxLines: 1),
                          ),
                          //UText.get(operatorList.isEmpty ?operatorName : str, UIColor.color_t1, 16.rpx);
                        // }),
                        Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3)
                      ],
                    )
                ),
            ),
          ],
        )
    );
  }

  Widget _renderSku() {
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _renderSpuType(),
          Container(
              margin: EdgeInsets.only(left: 16.rpx, right: 16.rpx),
              height: 1.rpx,
              color: UIColor.color_divider),
          ..._jSkuOptions1.asMap().keys.map((index) {
            return _renderOneSku(index);
          }).toList(),
          6.hspace,
        ],
      ),
    );
  }

  Widget _renderOneSku(int index) {
    var sku = _jSkuOptions1[index];
    return Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child:Row(
            children: [
              UText.get(sku["name"], UIColor.color_t1, 16.rpx),
              const Spacer(),
              UText.get(sku["val"], UIColor.color_t1, 16.rpx),
            ])
    );
  }

  Widget _renderSpuType() {
    return Container(
      height: 48.rpx,
      padding: EdgeInsets.symmetric(horizontal: 16.rpx),
      child: Row(
        children: [
          UText.get("货物类别", UIColor.color_t1, 16.rpx),
          const Spacer(),
          UText.get(_data["spu_product_name"] ?? "", UIColor.color_t1, 16.rpx),
        ],
      ),
    );
  }

  Widget _renderBottom() {
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _renderTotalWeight(),
          10.hspace,
          _renderTotalQty(),
          6.hspace,
        ],
      ),
    );
  }

  Widget _renderTotalWeight() {
    Widget rw;
    if( _unit == 2) {
      rw = Column(
        children: [
          Container(
              padding:EdgeInsets.fromLTRB(0,10.rpx,0,0),
              margin: EdgeInsets.fromLTRB(16.rpx,0,16.rpx,0),
              child: Row(
                children: [
                  UText.get("数量（吨）", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
                  const Spacer(),
                  NumberLayout(
                      controller: _amountLayoutController,
                      initNumber: _data['total_weight'] / 1000.0,
                      max: 10000,
                      editParentText: () => {
                        setState(() {

                        })
                      }
                  ),
                ],
              )
          ),
          Container(
              margin: EdgeInsets.only(left: 16.rpx,  right: 16.rpx),
              height: 1.rpx,
              color: UIColor.color_divider),
        ],
      );
    } else {
      rw = 0.wspace;
  }
    return rw;
  }

  Widget _renderTotalQty() {
    return Row(
      children: [
        16.wspace,
        UText.get("件数（件）", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
        const Spacer(),
        NumberLayout(
            controller: _numberLayoutController,
            initNumber: _data['qty'],
            max: 100000,
            min: 0,
            editParentText: () => { setState(() {

            })  }
        ),
        16.wspace,
      ],
    );
  }

  Widget _renderUploadImage(List<AssetEntity> list) {
    var width = (MediaQuery.of(context).size.width - 80.rpx) / 3;
    List<Widget> children = [];
    for (var element in list) {
      children.add(SizedBox(
        width: width,
        height: width,
        child: Stack(
          children: [
            Image(
                image: AssetEntityImageProvider(element),
                fit: BoxFit.cover,
                width: width,
                height: width),
            GestureDetector(
              onTap: () {
                _uploadHelper.remove(element);
              },
              child: Align(
                alignment: Alignment.topRight,
                child: SvgPicture.asset(R.image_delete, width: 28.rpx, height: 28.rpx),
              ),
            ),
          ],
        ),
      ));
    }
    return UBackground.getItemBlock([
      Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          UText.get("装货拍照", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
          SizedBox(width: 4.rpx),
          //UText.get("最多支持上传6张", UIColor.color_t3, 12.rpx),
        ],
      ),
      SizedBox(height: 10.rpx),
      Wrap(
        spacing: 10.rpx,
        runSpacing: 10.rpx,
        children: children,
      ),
      SizedBox(height: 10.rpx),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          MaterialButton(
            height: 42.rpx,
            minWidth: 120.rpx,
            color: UIColor.color_primary,
            elevation: 0,
            highlightColor: Colors.transparent,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(21.rpx)),
            ),
            child: UText.get("拍摄", Colors.white, UISize.main_text_size.rpx),
            onPressed: _uploadHelper.takePhoto,
          ),
          MaterialButton(
            height: 42.rpx,
            minWidth: 120.rpx,
            color: UIColor.color_primary,
            elevation: 0,
            highlightColor: Colors.transparent,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(21.rpx)),
            ),
            child: UText.get("手机相册选择", Colors.white, UISize.main_text_size.rpx),
            onPressed: _uploadHelper.pickImage,
          ),
        ],
      )
    ]);
  }

  Widget _renderRemark(){
    return Container(
        padding: EdgeInsets.only(left:16.rpx,top:12.rpx,right:16.rpx,bottom:12.rpx),
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child:Column(
          children: [
            Container(
              padding: EdgeInsets.only(top: 12.rpx, bottom: 12.rpx),
              alignment: Alignment.centerLeft,
              child:UText.get("备注信息", UIColor.color_t1, 16.rpx,textAlign:TextAlign.left,fw: FontWeight.w600),
            ),
            TextField(
                controller: _describeTextController,
                keyboardType: TextInputType.multiline,
                maxLines: null,
                maxLength: 60,
                decoration: const InputDecoration(
                    hintText: "请输入备注信息（选填）",
                    hintStyle:TextStyle(fontSize: 14,color: Color(0x4D000000)),
                    border:InputBorder.none
                )
            ),
          ],
        )
    );
  }

  dynamic _getPostJson() {
    var json = {};
    json["waybill_mission_id"] = _data["id"];
    var amount = _amountLayoutController.number;
    var unit = _numberLayoutController.number;
    if(_unit == 2) {
      json["weight"] = (amount * 1000).toInt();
    }
    json["qty"] = unit.toInt();
    json["remark"] = _describeTextController.text;
    // json["action"] = "load";
    var positionInfo = LocKit.instance.getData();
    if (positionInfo.isNotEmpty){
      json["lat"] = positionInfo["latitude"].toString();
      json["lng"] = positionInfo["longitude"].toString();
      json["address"] = positionInfo["address"];
    }
    if(_chooseList.isEmpty) {
      json["loaders"] = "";
    } else {
      List list = [];
      for(var i = 1;i<_chooseList.length;i++) {
        list.add({"id":_chooseList[i].id,"name":_chooseList[i].name});
      }
      json["loaders"] = jsonEncode(list);
    }
    return json;
  }

  _onClickSubmit() {
    if (_amountLayoutController.number == 0 && _unit == 2) {
      Tip.show("请输入数量");
      return ;
    }
    if (_numberLayoutController.number == 0) {
      Tip.show("请输入件数");
      return ;
    }
    var dialog = LoadingDialog(context);
    if (_uploadHelper.getImageUrls().isEmpty) {
          Tip.show("请上传图片");
          return ;
        }
        var json = _getPostJson();
        json["images"] = _uploadHelper.getImageUrls();
        CustomAlertDialog.showConfirmDialog(context, title:'装货确认' ,content: "确认已完成装货?", confirmText:'装货完成', onConfirm: () {
          dialog.show(text: "提交中...");
          var url = LoadApi.loadDing;
          if(_data["car_no"] == "") {
            url = LoadApi.preLoading;//无车装货
          }
          Api.submitx(context, url, data: json, progress: false, success: (data) {
            dialog.hide();
            Navigator.of(context).popUntil((route) => route.isFirst);
            eventBus.fire(RefreshOrderEvent());
            Toast.show(context, msg: "装货完成");
          }, failTip: "提交失败", fail: (_) {
            dialog.hide();
          });
        });
    //   _uploadHelper.upload(success: () {
    //     if (_uploadHelper.getImageUrls().isEmpty) {
    //       Tip.show("请上传图片");
    //       return ;
    //     }
    //     var json = _getPostJson();

    //     json["images"] = _uploadHelper.getImageUrls();
    //     CustomAlertDialog.show(context, content: "确定提交?", onConfirm: () {
    //       dialog.show(text: "提交中...");
    //       var url = "/waybill_mission/loading";
    //       if(widget.status == 0 || widget.status ==1) {
    //         url = "/waybill_mission/pre_loading";//无车装货
    //       }
    //       Api.submitx(context, url, data: json, progress: false, success: (data) {
    //         dialog.hide();
    //         Navigator.of(context).popUntil((route) => route.isFirst);
    //         eventBus.fire(RefreshOrderEvent());
    //       }, failTip: "提交失败", fail: (_) {
    //         dialog.hide();
    //       });
    //     });
    // }, fail: () {
    //   dialog.hide();
    //   Tip.show("图片上传失败");
    // });
  }

  _getLoadName() async {
    var _sp = await SharedPreferences.getInstance();
    var _loginInfo = jsonDecode(_sp.getString("login_info") ?? "");
    operatorName = _loginInfo["name"];
    operatorMobile = _loginInfo["mobile"];
    operatorId = _loginInfo["id"];
  }
}